const { SysMenu, sequelize } = require('../config/Sequelize')
const { CriteriaExample } = require('../utils/CriteriaExample')

/**
 * 查询菜单列表
 * @param {*} menu 
 * @returns 
 */
const selectMenuList = async (param) => {

  const example = new CriteriaExample(param)
  example.and()
  example.like('menuName', param.menuName)
  example.like('url', param.url)
  example.eq('visible', param.visible)
  if (param.type == 1) {
    example.and().not('menuType', 'F')
  }

  console.log(param)
  console.log(example.getWhere())
  const allMenus = await SysMenu.findAll({
    where: example.getWhere(),
    order: [['orderNum', 'ASC']],
  })

  // 构建树形结构
  const menuTree = [];

  function buildNode(m) {
    const node = m.toJSON();
    const children = allMenus.filter((menu) => menu.parentId === node.menuId);
    if (children.length > 0) {
      node.children = children.map((child) => buildNode(child));
    }
    return node;
  }

  // 查找根节点（假设根节点的 parent_id 为 0
  const rootNodes = allMenus.filter((menu) => menu.parentId === 0);

  rootNodes.forEach((rootNode) => {
    menuTree.push(buildNode(rootNode));
  });

  return { total: menuTree.length, data: menuTree }
}


/**
 * 根据菜单id查询菜单信息
 * @param {*} id 
 * @returns 
 */
const selectMenuById = async (id) => {
  const menu = await SysMenu.findOne({
    where: {
      menuId: id
    }
  })
  return menu
}

/**
 * 添加菜单信息
 * @param {*} menu 
 * @returns 
 */
const addMenu = (menu) => {
  return SysMenu.create(menu)
}

/**
 * 更新菜单信息
 * @param {*} menu 
 * @returns 
 */
const updateMenu = (menu) => {
  return SysMenu.update(menu, {
    where: {
      menuId: menu.menuId
    }
  })
}


/**
 * 删除菜单信息
 * @param {*} id 
 * @returns 
 */
const deleteMenu = (id) => {
  return SysMenu.destroy({
    where: { menuId: id }
  })
}


module.exports = {
  selectMenuList,
  selectMenuById,
  addMenu,
  updateMenu,
  deleteMenu
}